package cn.jiedh.app.meiweidk.welcome;

import android.Manifest;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.cmic.sso.sdk.auth.AuthnHelper;
import com.cmic.sso.sdk.auth.TokenListener;
import com.houhan.yijianlogin.AuthnHelperUtils;
import com.houhan.yijianlogin.Constant;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;
import org.xutils.ex.HttpException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.MainActivity;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.AlertDialog;
import cn.jiedh.app.meiweidk.Utils.UI.MyTBView;
import cn.jiedh.app.meiweidk.Utils.UI.SSODialog;
import cn.jiedh.app.meiweidk.Utils.config.ConfigUtils;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.BitmapUtil;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.LocationUtil;
import cn.jiedh.app.meiweidk.Utils.tool.MobileUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.Utils.tool.ValidateUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.buried.BuriedBean;
import cn.jiedh.app.meiweidk.entity.ImageCodeBean;
import cn.jiedh.app.meiweidk.entity.LoginAndRegisterBean;
import cn.jiedh.app.meiweidk.entity.UserBean;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionsManager;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionsResultAction;
import cn.jpush.android.api.JPushInterface;

/**
 * @name：
 * @author： 周毅
 * @phone： 15826080712
 * @createTime： 2017/12/8
 * @modifyTime： 2017/12/8
 * @explain：
 */

public class YJloginActivity extends BaseActivity {
    @BindView(R.id.yjlogin_layout)
    LinearLayout yjlogin_layout;
    @BindView(R.id.tvbtn)
    TextView Tvbtn;
    @BindView(R.id.tvmoney)
    TextView Tvmoney;
    @BindView(R.id.tvyongtu)
    TextView Tvyongtu;
    @BindView(R.id.ll_money)
    LinearLayout llMoney;
    @BindView(R.id.ll_yongtu)
    LinearLayout llYongtu;
    private TokenListener mListener;
    private AuthnHelper mAuthnHelper;
    private int tag;
    List<String> listmoney = new ArrayList<>();
    List<String> listyongtu = new ArrayList<>();
    OptionsPickerView MoneyPop;
    OptionsPickerView YongTuPop;
    boolean isYJlogin = false;
    private boolean bcode;
    private List<BuriedBean> buriedList;
    private boolean IsShowImgCode;
    private String img;
    private String imgKey;
    private Bitmap bitmap;

    private String token = "";

    @Override
    protected int getLayoutView() {
        return R.layout.yjlogin;
    }

    @Override
    protected void initView(View view) {
        Tvmoney.setText(SPUtils.getmoney()+"元");
        Tvbtn.setEnabled(false);
        mAuthnHelper = AuthnHelper.getInstance(this.getApplicationContext());
        mAuthnHelper.setDebugMode(true);
        mListener = new TokenListener() {
            @Override
            public void onGetTokenComplete(JSONObject jObj) {
                try {
                    if (jObj != null) {
                        if (tag == 1) { //预取号请求结果
                            dismissLoadingDialog();
                            if (jObj.has("resultCode")) {
                                if (jObj.getString("resultCode").equals("103000")) {  //成功
                                    yjlogin();
                                } else { //失败弹出注册登录dialog
//                                    getImageCode();
                                }
                            }
                        } else if (tag == 2) { //显示登录
                            if (jObj.has("resultCode")) {
                                if (jObj.getString("resultCode").equals("103000")) {  //成功
                                    if (jObj.has("token")) {
                                        token = jObj.getString("token");
                                        mHandler.sendEmptyMessage(3);
                                        SPUtils.saveBuried("login", "9", "一键登录:成功", "",
                                                "", "", "", "");
//                                        yjlogin_layout.setVisibility(View.INVISIBLE);
                                    }
                                } else if (jObj.getString("resultCode").equals("102121")) {//失败弹出注册登录dialog

                                } else {
                                    SPUtils.saveBuried("login", "9", "一键登录:失败", "",
                                            "", "", "", "");
//                                    getImageCode();
                                }
                            }
                        }

                    }
                } catch (Exception e) {
                    SPUtils.saveBuried("login", "9", "一键登录:异常", "",
                            "", "", "", "");
                    e.printStackTrace();
                }

            }
        };
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    showssodialog(IsShowImgCode);
                    break;
                case 2:  //显示图像验证码
                    showssodialog1(IsShowImgCode, bitmap);
                    break;
                case 3:
                    ssologin(token); //获取到token调用我们的回调接口
                    break;
                default:
                    break;
            }
        }

    };

    private void getImageCode() {
        Map<String, Object> map = new HashMap<>();
        request(activity, UrlUtils.IMAGECODE, map, false, new ResponseSuccess<ImageCodeBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<ImageCodeBean> response) {
                if (3 == response.getCode()) { //显示图形验证码
                    img = response.getData().getImg();
                    imgKey = response.getData().getImgKey();
                    bitmap = BitmapUtil.stringtoBitmap(img);
                    IsShowImgCode = true;
                    mHandler.sendEmptyMessage(2);

                } else { //不显示
                    IsShowImgCode = false;
                    mHandler.sendEmptyMessage(1);
                }
            }
        });
    }

    //调出本地登录注册页面
    public void showssodialog(boolean isshowimgcode) {
        SSODialog ssoDialog = new SSODialog(this, isshowimgcode, new SSODialog.OnCenterItemClickListener() {
            @Override
            public void OnCenterItemClick(SSODialog dialog, String phone, String code, int tag, MyTBView myTBView, String imgcode) {
                if (tag == 1) {
                    getcode(phone, myTBView, imgcode);
                } else if (tag == 2) {
                    login(phone, code, dialog);
                }
            }

            @Override
            public void RefreshImg() {
//                getImageCode();
            }
        });
        ssoDialog.show();
    }

    SSODialog ssoDialog;

    //调出本地登录注册页面
    public void showssodialog1(boolean isshowimgcode, Bitmap bitmap) {
        if (ssoDialog != null && ssoDialog.isShowing()) {
            ssoDialog.setBitmap(bitmap);
        } else {
            ssoDialog = new SSODialog(this, bitmap, isshowimgcode, new SSODialog.OnCenterItemClickListener() {
                @Override
                public void OnCenterItemClick(SSODialog dialog, String phone, String code, int tag, MyTBView myTBView, String imgcode) {
                    if (tag == 1) {
                        getcode(phone, myTBView, imgcode);
                    } else if (tag == 2) {
                        login(phone, code, dialog);
                    }
                }

                @Override
                public void RefreshImg() {
//                    getImageCode();
                }
            });
            ssoDialog.show();
        }
    }

    //验证码登录
    private void login(String phone, String code, SSODialog ssoDialog) {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", code);
//        LocationManager locationManager = (LocationManager) this.getApplication().getSystemService(Context.LOCATION_SERVICE);
//        Double[] doubles = LocationUtil.getGpsLocation(this.getApplicationContext(), locationManager);
        Double[] doubles = LocationUtil.location;
        if (doubles != null) {
            Double lat = doubles[0];
            Double lng = doubles[1];
            map.put("longitude", lng);
            map.put("latitude", lat);
        }

        request(activity, UrlUtils.VERIFICATIONLOGIN, map, true, new ResponseSuccess<LoginAndRegisterBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<LoginAndRegisterBean> response) {
                dismissLoadingDialog();
                T.showShortToast(response.getMessage());
                if (0 == response.getCode()) {
                    ssoDialog.dismiss();
                    SPUtils.saveToApp(activity,phone,SPUtils.getmoney());
                    SPUtils.saveUser(phone, response.getData().getToken());
                    ActivityUtil.next(activity, MainActivity.class);
                    JPushInterface.setAlias(activity, SPUtils.getPhone(), null);
//                    EventScreen eventScreen = new EventScreen(Constant.NEWUSER, "");
//                    EventUtils.getDefault().forward(eventScreen);
                    finish();
                }
                L.i("token：" + response.getData().getToken());
            }
        });
    }

    /**
     * 登录验证码
     *
     * @param phone
     */
    private void getcode(String phone, MyTBView myTBView, String imgcode) {
        myTBView.start();
        SPUtils.saveBuried("click","0","引导页新用户专享-获取验证码","true",
                "引导页新用户专享","","","");
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("imgKey", imgKey);
        map.put("imgCode", imgcode);
        request(activity, UrlUtils.LOGINSMSCODE, map, false, new ResponseSuccess() {
            @Override
            public void onRequestSucceed(BaseResponse response) {
                if (response.getCode() == 0) {
                    T.showShortToast(response.getMessage());
                    bcode = true;
                }
            }
        });
    }

    //服务器登录接口
    private void ssologin(String token) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", "");
        map.put("thirdPartyAppId", Constant.APP_ID);
        map.put("thirdPartyToken", token);
        showLoadingDialog();
        request(this, UrlUtils.SSOLOGIN, map, true, new ResponseSuccess<UserBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<UserBean> response) {
                SPUtils.saveToApp(activity,response.getData().getPhone(),SPUtils.getmoney());
                SPUtils.saveUser(response.getData().getPhone(), response.getData().getToken());
                ActivityUtil.next(activity, MainActivity.class);
                JPushInterface.setAlias(activity, response.getData().getPhone(), null);
//                EventScreen eventScreen = new EventScreen(Constant.NEWUSER, "");
//                EventUtils.getDefault().forward(eventScreen);
                finish();
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
//                yjlogin_layout.setVisibility(View.VISIBLE);
                T.showShortToast(msg);
            }
        });
    }

    //判断权限
    public void getroot() {
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this, new String[]{
                Manifest.permission.READ_PHONE_STATE}, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                yjlogin();
            }

            @Override
            public void onDenied(String permission) {
                showdialog();
            }
        });
    }

    //未开启权限弹出dialog
    private void showdialog() {
        new AlertDialog(this).builder().setTitle("未开启权限").setMsg("跳转至设置界面").setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        }).setPositiveButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MobileUtils.getAppDetailSettingIntent(YJloginActivity.this);

            }
        }).show();
    }

    //调起一键登录页面
    private void yjlogin() {
        tag = 2;
        AuthnHelperUtils.displayLogin(mAuthnHelper, mListener, tag);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void initData() {
        if (SPUtils.getmoneylist().size() > 0 && SPUtils.getyongtulist().size() > 0) {
            for (int i = 0; i < SPUtils.getmoneylist().size(); i++) {
                if (i == SPUtils.getmoneylist().size() - 1) {
                    listmoney.add(SPUtils.getmoneylist().get(i).getName());
                } else {
                    listmoney.add(SPUtils.getmoneylist().get(i).getName() + "元");
                }
            }
            for (int i = 0; i < SPUtils.getyongtulist().size(); i++) {
                listyongtu.add(SPUtils.getyongtulist().get(i).getName());
            }
            initpop();
        }
        initevent();
//        getmoneyandyontu();
    }

    private void initevent() {
        Tvmoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                buttonchange();
            }
        });
        Tvyongtu.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                buttonchange();
            }
        });

    }

    public void buttonchange() {
        String smoney = Tvmoney.getText().toString().trim();
        String syongtu = Tvyongtu.getText().toString().trim();
        if (!TextUtils.isEmpty(smoney) && !TextUtils.isEmpty(syongtu)) {
            Tvbtn.setEnabled(true);
            Tvbtn.setBackground(getResources().getDrawable(R.drawable.shape_btn_red));
        } else {
            Tvbtn.setEnabled(false);
            Tvbtn.setBackground(getResources().getDrawable(R.drawable.shape_gray1_bg));
        }

    }

    public void initpop() {
        MoneyPop = new OptionsPickerView.Builder(this, (options1, options2, options3, v) -> {
            Tvmoney.setText(listmoney.get(options1));
            SPUtils.saveToApp(activity, ConfigUtils.MONEY, SPUtils.getmoneylist().get(options1).getValue() + "");
        }).setOutSideCancelable(false)
                .setDividerColor(R.color.hint3_text_color)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        YongTuPop = new OptionsPickerView.Builder(this, (options1, options2, options3, v) -> {
            Tvyongtu.setText(listyongtu.get(options1));
            SPUtils.saveToApp(activity, ConfigUtils.TYPE, SPUtils.getyongtulist().get(options1).getName()+"");
        }).setOutSideCancelable(false)
                .setDividerColor(R.color.hint3_text_color)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        MoneyPop.setPicker(listmoney);
        YongTuPop.setPicker(listyongtu);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

//    //预取号
//    public void pregetphone() {
//        tag = 1;
//        showLoadingDialog();
//        AuthnHelperUtils.preGetPhone(mAuthnHelper, mListener, tag);
//    }

    @OnClick({R.id.ll_yongtu, R.id.tvbtn, R.id.ll_money})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_money:
                if (MoneyPop != null) {
                    MoneyPop.show();
                }
                break;
            case R.id.ll_yongtu:
                if (YongTuPop != null) {
                    YongTuPop.show();
                }
                break;
            case R.id.tvbtn:
                String smoney = Tvmoney.getText().toString().trim();
                String syongtu = Tvyongtu.getText().toString().trim();
                if (ValidateUtils.isgotonext(smoney, syongtu)) {
                        yjlogin();
                }
                break;
        }
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
